<template>
  <div class="route-panel">
    <div class="route-panel-header">
      <div>
        <h3>航线规划</h3>
        <p class="route-panel-sub">自定义航线并绘制地图航点</p>
      </div>
      <button class="route-close" @click.stop="emit('close')">✖</button>
    </div>
    <div class="route-panel-body">
      <div class="route-form-row">
        <label>航线名称</label>
        <input
          class="route-input"
          :value="routeForm.name"
          placeholder="请输入航线名称"
          @input="handleBaseInput('name', $event)"
        />
      </div>
      <div class="route-form-row">
        <label>航线描述</label>
        <textarea
          class="route-input"
          rows="2"
          :value="routeForm.description"
          placeholder="填写任务或注意事项"
          @input="handleBaseInput('description', $event)"
        ></textarea>
      </div>
      <div class="route-form-row">
        <label>预设时长 (分钟)</label>
        <input
          class="route-input"
          type="number"
          min="0"
          :value="routeForm.duration"
          placeholder="请输入预估耗时"
          @input="handleBaseInput('duration', $event)"
        />
      </div>
      <div class="route-actions">
        <button
          class="route-action primary"
          :disabled="routeDrawingActive"
          @click.stop="emit('start-drawing')"
        >
          {{ routeDrawingActive ? "绘制中..." : "开始绘制" }}
        </button>
        <button class="route-action" @click.stop="emit('clear')">
          清空航线
        </button>
        <button class="route-action" @click.stop="emit('load-route')">
          加载航线
        </button>
      </div>
      <div class="waypoint-section">
        <div class="waypoint-header">航点列表</div>
        <div v-if="!routeForm.waypoints.length" class="waypoint-empty">
          暂未生成航点，点击“开始绘制”后在地图上标注航线。
        </div>
        <div
          v-for="(wp, index) in routeForm.waypoints"
          :id="`waypoint-${index}`"
          :key="wp.id"
          class="waypoint-item"
          :class="{ active: routeEditingIndex === index }"
          @click.stop="emit('focus-waypoint', index)"
        >
          <div class="waypoint-title">
            <span>航点 {{ index + 1 }}</span>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除航点"
              placement="top"
            >
              <i
                class="iconfont icon-shanchu"
                style="cursor: pointer; color: #f53f3f"
                @click.stop="emit('remove-waypoint', index)"
              ></i>
            </el-tooltip>
          </div>
          <div class="waypoint-grid">
            <label>名称</label>
            <input
              class="route-input"
              :value="wp.name"
              placeholder="航点名称"
              @input="handleWaypointChange(index, 'name', $event)"
            />
            <label>纬度</label>
            <input
              class="route-input"
              type="number"
              step="0.000001"
              :value="wp.lat"
              @change="handleWaypointChange(index, 'lat', $event)"
            />
            <label>经度</label>
            <input
              class="route-input"
              type="number"
              step="0.000001"
              :value="wp.lng"
              @change="handleWaypointChange(index, 'lng', $event)"
            />
            <label>高度</label>
            <input
              class="route-input"
              type="number"
              step="1"
              min="0"
              :value="wp.altitude"
              @change="handleWaypointChange(index, 'altitude', $event)"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="route-panel-footer">
      <div class="route-footer-actions">
        <button class="route-kml" @click.stop="emit('download')">
          保存为KML文件
        </button>
        <button class="route-submit" :disabled="loading.value" @click.stop="saveRoute">
          {{ loading.value ? '保存中...' : '上传航线' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineEmits, defineProps, reactive, toRefs } from "vue";
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { flightRouteService } from '@/api/modules/flightRoute';

const props = defineProps({
  routeForm: {
    type: Object,
    required: true,
  },
  routeDrawingActive: {
    type: Boolean,
    default: false,
  },
  routeEditingIndex: {
    type: Number,
    default: null,
  },
});

const emit = defineEmits([
  "close",
  "start-drawing",
  "clear",
  "focus-waypoint",
  "remove-waypoint",
  "update-waypoint-field",
  "update-field",
  "download",
  "submit",
  "load-route",
  "route-saved",
  "route-updated",
]);

const { routeForm, routeDrawingActive, routeEditingIndex } = toRefs(props);
const loading = reactive({ value: false });

const extractValue = (evt) => {
  if (!evt || !evt.target) return "";
  return evt.target.value;
};

const handleBaseInput = (field, evt) => {
  emit("update-field", { field, value: extractValue(evt) });
};

const handleWaypointChange = (index, field, evt) => {
  emit("update-waypoint-field", {
    index,
    field,
    value: extractValue(evt),
  });
};

// 保存航线
const saveRoute = async () => {
  if (routeForm.value.waypoints.length < 2) {
    ElMessage.warning('航线至少需要2个航点');
    return;
  }
  
  // 验证航点坐标
  for (const wp of routeForm.value.waypoints) {
    if (!wp.lat || !wp.lng) {
      ElMessage.warning('所有航点必须有有效的经纬度坐标');
      return;
    }
  }
  
  loading.value = true;
  try {
    // 准备符合后端schema的数据
    const formData = {
      name: routeForm.value.name,
      description: routeForm.value.description,
      drone_id: routeForm.value.drone_id,
      estimated_time: routeForm.value.duration, // 转换duration为estimated_time
      waypoints: routeForm.value.waypoints.map((wp, idx) => ({
        alt: Number(wp.altitude) || 0, // 转换altitude为alt
        lat: wp.lat,
        lng: wp.lng,
        name: (wp.name || `航点${idx + 1}`).trim()
      }))
    };
    
    let response;
    if (routeForm.value.id) {
      // 更新现有航线
      response = await flightRouteService.updateRoute(routeForm.value.id, formData);
    } else {
      // 创建新航线
      response = await flightRouteService.createRoute(formData);
    }
    console.log("航线更新",response);
    ElMessage.success(routeForm.value.id ? '航线更新成功' : '航线创建成功');
    emit('route-saved', response);
    // 发送更新事件而不是关闭面板，这样可以保留其他显示的航线
    if (routeForm.value.id) {
      emit('route-updated', response);
    } else {
      emit('close');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '保存航线失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.route-panel {
  position: absolute;
  top: 12px;
  right: 45px;
  width: 320px;
  max-height: calc(100% - 24px);
  display: flex;
  flex-direction: column;
  background: rgba(17, 24, 39, 0.92);
  border-radius: 18px;
  box-shadow: 0 24px 48px rgba(0, 0, 0, 0.45);
  padding: 20px 18px;
  z-index: 904;
  overflow: hidden;
  color: #f9fafb;
  backdrop-filter: blur(10px);
}

.route-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}

.route-panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #f3f4f6;
}

.route-panel-sub {
  margin: 4px 0 0;
  font-size: 12px;
  color: #9ca3af;
}

.route-close {
  border: none;
  background: transparent;
  color: #9ca3af;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
}

.route-close:hover {
  color: #e5e7eb;
}

.route-panel-body {
  flex: 1;
  overflow-y: auto;
  margin-top: 12px;
  padding-right: 4px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.route-form-row {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.route-form-row label {
  font-size: 13px;
  color: #d1d5db;
}

.route-input {
  width: 100%;
  border: 1px solid rgba(148, 163, 184, 0.4);
  border-radius: 8px;
  padding: 8px 10px;
  font-size: 13px;
  background: rgba(17, 24, 39, 0.18);
  color: #f3f4f6;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.route-input:focus {
  outline: none;
  border-color: #2563eb;
  box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
}

.route-actions {
  display: flex;
  gap: 8px;
}

.route-action {
  flex: 1;
  border: 1px solid rgba(148, 163, 184, 0.4);
  border-radius: 8px;
  padding: 8px 12px;
  font-size: 13px;
  color: #e5e7eb;
  background: rgba(31, 41, 55, 0.6);
  cursor: pointer;
  transition: all 0.2s ease;
}

.route-action.primary {
  background: #2563eb;
  border-color: #2563eb;
  color: #fff;
}

.route-action.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.route-action:not(.primary):hover {
  border-color: #9ca3af;
}

.route-action:disabled,
.route-action[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

.waypoint-section {
  border: 1px solid rgba(148, 163, 184, 0.25);
  border-radius: 10px;
  background: rgba(30, 41, 59, 0.65);
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.waypoint-header {
  font-size: 13px;
  font-weight: 600;
  color: #f3f4f6;
}

.waypoint-empty {
  font-size: 12px;
  color: #9ca3af;
}

.waypoint-item {
  padding: 10px;
  border-radius: 8px;
  background: rgba(31, 41, 55, 0.6);
  border: 1px solid rgba(148, 163, 184, 0.25);
  display: flex;
  flex-direction: column;
  gap: 8px;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
}

.waypoint-item.active {
  border-color: rgba(59, 130, 246, 0.75);
  background: rgba(30, 64, 175, 0.35);
  box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.4);
}

.waypoint-title {
  font-size: 13px;
  font-weight: 600;
  color: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.waypoint-grid {
  display: grid;
  grid-template-columns: 60px 1fr;
  gap: 6px 10px;
  align-items: center;
}

.waypoint-grid label {
  font-size: 12px;
  color: #cbd5f5;
}

.route-panel-footer {
  margin-top: 12px;
}

.route-footer-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.route-kml {
  border: 1px solid rgba(148, 163, 184, 0.6);
  background: rgba(59, 130, 246, 0.12);
  color: #93c5fd;
  padding: 9px 16px;
  border-radius: 10px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.route-kml:hover {
  background: rgba(59, 130, 246, 0.2);
  border-color: rgba(59, 130, 246, 0.6);
  color: #bfdbfe;
}

.route-submit {
  border: none;
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  color: #fff;
  padding: 10px 18px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 13px;
  box-shadow: 0 10px 24px rgba(37, 99, 235, 0.35);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.route-submit:hover {
  transform: translateY(-1px);
  box-shadow: 0 12px 24px rgba(37, 99, 235, 0.3);
}

.route-panel-enter-active,
.route-panel-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.route-panel-enter-from,
.route-panel-leave-to {
  opacity: 0;
  transform: translateX(12px);
}

@media (max-width: 1080px) {
  .route-panel {
    width: calc(100% - 24px);
    top: auto;
    bottom: 12px;
    right: 12px;
    left: 12px;
    max-height: 360px;
  }
}
</style>
